﻿using System.Windows;
using System.Windows.Controls;

namespace SuperGo.Silverlight {
	public static class ExtensionMethods {
		public static void SetVisible(this FrameworkElement element, bool visible) {
			element.Visibility = visible ? Visibility.Visible : Visibility.Collapsed;
		}

		public static void SetVisible(ref Visibility visibility, bool visible) {
			visibility = visible ? Visibility.Visible : Visibility.Collapsed;
		}

		public static bool IsVisible(this Visibility visibility) {
			return visibility == Visibility.Visible;
		}

		public static void SetVisible(this FrameworkElement element, bool makeVisible, Panel visibleParent, Panel invisibleParent) {
			if (element == null)
				return;
			
			bool existsInVisible = visibleParent.Children.Contains(element);
			bool existsInInvisible = invisibleParent.Children.Contains(element);
			
			if (makeVisible) {
				if (existsInInvisible)
					invisibleParent.Children.Remove(element);
				if (!existsInVisible)
					visibleParent.Children.Add(element);
				element.Visibility = Visibility.Visible;
			} else {
				// if we're trying to make it invisible and it exists in visible then remove it
				if (existsInVisible)
					visibleParent.Children.Remove(element);
				if (!existsInInvisible)
					invisibleParent.Children.Add(element);
			}

			element.Tag = makeVisible ? "visible" : "invisible";
		}

		public static bool IsVisible(this FrameworkElement element) {
			bool tagIsInvisible = false;
			if (element.Tag != null)
				tagIsInvisible = element.Tag.Equals("invisible");
			
			bool visiblePropertyIsVisible = element.Visibility == Visibility.Visible;

			// it's only visible if the visible property is visible and the tag isn't invisible
			return visiblePropertyIsVisible && !tagIsInvisible;
		}
	}
}
